function MapLoader () {  
	return new Promise((resolve, reject) => {
        if (parent.AMap) {
            window.AMap = parent.AMap;
        }
		if (window.AMap) {
			resolve(window.AMap)
        }
	})
}
coordtransform.bd09towgs84 = function (lng, lat) {
    var gcj = coordtransform.bd09togcj02(lng, lat);
    return coordtransform.gcj02towgs84(gcj[0], gcj[1]);
}
coordtransform.wgs84tobd09= function (lng, lat) {
    var gcj = coordtransform.wgs84togcj02(lng, lat);
    return coordtransform.gcj02tobd09(gcj[0], gcj[1]);
}

Vue.component('amap-picker', {
  template: `
        <div id="all" style="height:100%">
        <div class="posInput">
            <el-input style="width:100%"
                        id="tipinput"
                        class="form-control input-style"
                        type="text"
                        placeholder="请输入搜索地址"
                        prefix-icon="el-icon-search"
                        v-model="MapAdress"
                        @input="inputMapAdress">
            </el-input>
        </div>
        <div id="allmap"></div>
        <div class="posSubmit" v-if="false">
            <el-input style="width:100%"
                        id="insureinput"
                        class="form-control input-style"
                        type="text"
                        v-model="insureAdress">
            </el-input>
            <el-button type="primary" size="large" style="padding: 10px 20px" @click="insureMapAdress">确定</el-button>
        </div>
        <div class="status">{{thisPosition.lng}}|{{thisPosition.lat}}|{{insureAdress}}</div>
        <el-button class="saveBtn" type="primary" size="large" @click="confirm">保存</el-button>
        </div>
    `,
  props: {
    lnglat: {
      type: Array,
      validator: (value) => {
        return value.length === 2
      }
    },
    pickerType: {
        type: String,
        default: 'gcj02'
    },
    address: {
        type: String,
        default: ''
    }
  },
  data() {
    return {
        map: null,
        thisPosition: {
            lng: this.lnglat[0],
            lat: this.lnglat[1]
        },
        mapinitCode:0, //地理编码:1;地理逆编码:2
        MapAdress:'',
        insureAdress:'',
    };
  },
  mounted: function () {
    this.mapinitCode = 1;
    this.layers = '';
    if (this.pickerType == 'wgs84') {
        this.layers = [
            'http://t{0,1,2,3,4,5,6}.tianditu.gov.cn/DataServer?T=vec_w&tk=c27c613115979d179e2794dcb248c29d&x=[x]&y=[y]&l=[z]',
            //'http://t{0,1,2,3,4,5,6}.tianditu.gov.cn/DataServer?T=img_w&tk=c27c613115979d179e2794dcb248c29d&x=[x]&y=[y]&l=[z]',
            'http://t{0,1,2,3,4,5,6}.tianditu.gov.cn/DataServer?T=cva_w&tk=c27c613115979d179e2794dcb248c29d&x=[x]&y=[y]&l=[z]'].map((n, i) => {
            return new AMap.TileLayer({
                getTileUrl: n,
                blend: true,
                zooms: [3, 18],
                zIndex: i + 2
            });
         })
    } else if (this.pickerType == 'bd09') {
        this.layers = [
            'https://webst0{1,2,3,4}.is.autonavi.com/appmaptile?style=6&x=[x]&y=[y]&z=[z]',
            'https://webst0{1,2,3,4}.is.autonavi.com/appmaptile?style=8&x=[x]&y=[y]&z=[z]'
        ].map((n, i) => {
            return new AMap.TileLayer({
                getTileUrl: n,
                blend: true,
                zooms: [3, 18],
                zIndex: i + 2
            });
         })
    };
    this.mapinit(...this.lnglat);
  },
  methods: {
    inputMapAdress(e){
        // console.log(e)
        this.MapAdress = e
    },
    insureMapAdress(){//确定修改地址
        console.log(this.insureAdress)
        this.$confirm('此操作为修改地址, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            let data = {}
            data.id=this.rowData.id;
            data.longitute = this.thisPosition.lng
            data.latitude = this.thisPosition.lat
            data.address = this.insureAdress
            updateCompanyAddress(data).then(res => {
                if(res.data.code ==  1){
                    this.$message({
                        message: '更新地址成功！',
                        type: 'success'
                    });
                }else{
                    this.$message.error('修改失败');
                }

            })
        })
    },
    /*
    mapMarker(longitute,latitude){ //指针
        let that = this
        //加载PositionPicker，loadUI的路径参数为模块名中 'ui/' 之后的部分
        AMapUI.loadUI(['misc/PositionPicker'], function(PositionPicker) {
            // var map = new AMap.Map('allmap',{
            //     zoom:16,
            //     layers: that.layers
            // })
            map = that.map;
            // 传入经纬度，设置地图中心点
            var position = '';
            if(that.mapinitCode == 1){
                position = new AMap.LngLat(longitute,latitude);  // 标准写法
                map.setCenter(position);
            } else if(that.mapinitCode == 2){
                position = new AMap.LngLat(latitude,longitute);  // 标准写法
                map.setCenter(position);
            }

            var positionPicker = new PositionPicker({
                mode:'dragMap',//设定为拖拽地图模式，可选'dragMap'、'dragMarker'，默认为'dragMap'
                map:map//依赖地图对象
            });
            //TODO:事件绑定、结果处理等
            positionPicker.on('success', function(positionResult) {
                console.log("positionResult",positionResult)
                that.thisPosition.lng = positionResult.position.lng
                that.thisPosition.lat = positionResult.position.lat
                that.insureAdress = positionResult.address;
                that.$emit('confirm', {
                    lnglat: that.thisPosition,
                    address:  that.insureAdress
                });
            });
            positionPicker.on('fail', function(positionResult) {
                // 海上或海外无法获得地址信息
                console.log(`定位失败:` + positionResult)
            });
            positionPicker.start();
            map.panBy(0, 1);
        });
    },
    */
    mapMarker(longitute,latitude){ //指针
        let vm = this;
        if (!vm.marker) {
            vm.marker = new AMap.Marker({
                map: vm.map,
                position: new AMap.LngLat(longitute,latitude),
                icon: './img/red.png',
                offset: new AMap.Pixel(-22, -57),
                draggable: true
            });
            vm.marker.on('dragend', function (e) {
                var lnglat = vm.marker.getPosition();
                vm.map.setCenter(lnglat);
                vm.getAddressByLngLat(lnglat.lng, lnglat.lat);
            });
        } else {
            vm.marker.setPosition(new AMap.LngLat(longitute,latitude));
        }
    },
    getAddressByLngLat: function (lng, lat) {
        var vm = this;
        vm.thisPosition.lng = lng;
        vm.thisPosition.lat = lat;
        var gdPosition = vm.poiVertFandT(this.pickerType, 'gcj02', [lng, lat]);
        AMap.plugin(['AMap.Geocoder'], function () {
            let geocoder = new AMap.Geocoder();
            geocoder.getAddress(gdPosition, function(status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    vm.insureAdress = result.regeocode.formattedAddress;
                }
            })
        })
    },
    mapinit: function (longitute,latitude) { //经纬度定位
        let that = this;
        MapLoader().then(AMap => {
            var map = new AMap.Map("allmap", {
                center: [longitute, latitude],
                resizeEnable: true,
                zoom: 16,
                layers: that.layers
            });
            that.map = map;

            AMap.plugin(['AMap.Autocomplete','AMap.PlaceSearch'],function(){
                // map.addControl(new AMap.ToolBar())
                // map.addControl(new AMap.Scale())
                var autoOptions = {
                    city: "江阴市", //城市，默认全国
                    input: "tipinput"//使用联想输入的input的id（也就是上边那个唯一的id）
                };
                var autocomplete= new AMap.Autocomplete(autoOptions);
                var placeSearch = new AMap.PlaceSearch({
                    city: '江阴市',
                    map: map
                })
                AMap.event.addListener(autocomplete, "select", function (e) {
                    var position = that.poiVertFandT('gcj02', that.pickerType, [e.poi.location.lng, e.poi.location.lat]);
                    that.thisPosition.lng = position[0];
                    that.thisPosition.lat = position[1];

                    that.insureAdress = e.poi.district + e.poi.address
                    console.log(that.insureAdress)
                    that.map.setZoom(16);
                    map.setCenter(new AMap.LngLat(...position));
                    that.mapMarker(...position)
                });
            });
            that.mapMarker(longitute,latitude);
            if (that.address) {
                that.insureAdress = that.address;
            } else {
                that.getAddressByLngLat(longitute,latitude);
            }
        })

    },
    maplocal (address){ //地理逆编码
        let that = this
        MapLoader().then(AMap => {
            AMap.plugin(['AMap.Geocoder'], function () {
                let geocoder = new AMap.Geocoder();
                geocoder.getLocation(address, (status, result) => {
                    console.log(address);
                    if (status === 'complete' && result.geocodes.length) {
                        console.log(result)
                        const lnglat = result.geocodes[0].location;

                        const lat = lnglat.lat;
                        const lng = lnglat.lng;
                        that.mapinit(lat, lng)	//tips：使用地理逆编码，此时解析出的经纬度位置也应逆换
                    } else {
                        console.log(result)
                    }
                });
            })
        })
    },
    poiVertFandT (from, to, lnglat) {
        if (from == to) {
            return lnglat;
        } else {
            return coordtransform[from + 'to' + to](...lnglat);
        }
    },
    confirm: function () {
        var lnglat = [this.thisPosition.lng, this.thisPosition.lat];
        var result = {
            lnglat,
            type: this.pickerType,
            address: this.insureAdress,
            lnglat_wgs84: this.poiVertFandT(this.pickerType, 'wgs84', lnglat),
            lnglat_gcj02: this.poiVertFandT(this.pickerType, 'gcj02', lnglat),
            lnglat_bd09: this.poiVertFandT(this.pickerType, 'bd09', lnglat),
        };
        this.$emit('confirm', result);
    }
  }

});
